package com.ad.api.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.example.support.redis.RedisHelper;
import com.example.support.spring.SpringEnvHolder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Deprecated//TODO remove
@Component
public class SmsSendUtils {
    private static class LogUtils { static final org.slf4j.Logger smsLog = org.slf4j.LoggerFactory.getLogger(SmsSendUtils.class); }
    private static final String product = "Dysmsapi";
    private static final String domain = "dysmsapi.aliyuncs.com";
    /*

    private static   String accessKeyId="LTAI5tDyX4v7BvVYXhbERAZy";

    private static   String accessKeySecret ="nGhSeNbCCAARsUrfXZ8hERwmBOL3Oy";

    private static   String defautempleteId ="SMS_251116142" ;

    private static   String signName= "韦尔奇实业" ;
   */

     private static   String accessKeyId;
     @Value("${sms.accessKeyId}")
     public void setAccessKeyId(String accessKeyId){
     this.accessKeyId=accessKeyId;
     }

     private static   String accessKeySecret ;
     @Value("${sms.accessKeySecret}")
     public void setAccessKeySecret(String accessKeySecret){
         this.accessKeySecret=accessKeySecret;
     }

     private static   String defautempleteId  ;
     @Value("${sms.defautempleteId}")
     public void setDefautempleteId(String defautempleteId){
         this.defautempleteId=defautempleteId;
     }

     private static   String signName  ;
     @Value("${sms.signName}")
     public void setSignName(String signName){
         this.signName=signName;
     }


    //手机验证码次数
    private static final String SMS_SEND_TIMES = "sms:send.times.";
    //手机验证码发送
    private static final String SMS_SEND_CODE = "sms:send.code.";

    //短信发送有效时间
    private static final int expire = 3 * 60;
    //短信最多每人发送次数每天
    private static final int expireTimes = 15;


    public static boolean sendSmsCode(String mobile){
        //判断手机号是否发送次数已超过
        try{
            String timeKeys = SMS_SEND_TIMES+mobile;
            String smsKeys = SMS_SEND_CODE+mobile;
            String smsCode = RedisHelper.stringRedisTemplate().opsForValue().get(smsKeys);
            Integer times = (Integer) RedisHelper.redisTemplate().opsForValue().get(timeKeys);
            //long timeKeysTime = DateKit.strToDate(DateKit.getFormatDate(new Date(),"yyyy-MM-dd 23:59:59"),"yyyy-MM-dd HH:mm:ss").getTime() - System.currentTimeMillis();
            long timeKeysTime = LocalDateTime.now().until(LocalDateTime.of(LocalDate.now(), LocalTime.MAX), ChronoUnit.MILLIS);

            if(SpringEnvHolder.isDevEnv() || (
                    (times == null || times < expireTimes) && StringUtils.isEmpty(smsCode)
            )){
                String code = sendSmsCode0(mobile);
                if(StringUtils.isEmpty(code)){
                    return false;
                }else{
                    RedisHelper.stringRedisTemplate().opsForValue().increment(timeKeys, 1);
                    RedisHelper.stringRedisTemplate().expire(timeKeys, timeKeysTime/1000, TimeUnit.SECONDS);
                    RedisHelper.stringRedisTemplate().opsForValue().set(smsKeys, code, expire, TimeUnit.SECONDS);
                    return true;
                }
            } else {
                LogUtils.smsLog.warn("短信验证码发送, mobile={}, 次数：{}",mobile,times);
            }
        }catch (Exception e){
            LogUtils.smsLog.error("短信验证码发送异常, mobile={}",mobile,e);
        }
        return false;
    }

    public static boolean verfySmsCode(String mobile,String code){
        try{
            if("8888".equals(code) && SpringEnvHolder.isDevEnv()){
                return true;
            }

            String smsKeys = SMS_SEND_CODE+mobile;
            String smsCode = RedisHelper.stringRedisTemplate().opsForValue().get(smsKeys);
            if(StringUtils.isEmpty(smsCode) || !smsCode.replaceAll("\"","").equals(code)){
                LogUtils.smsLog.warn("短信验证码校验失败, mobile={}, expectCode={}, code={}",mobile,smsCode,code);
                return false;
            }else{
                LogUtils.smsLog.debug("短信验证码校验成功, mobile={}, expectCode={}, code={}",mobile,smsCode,code);
                return true;
            }
        }catch (Exception e){
            LogUtils.smsLog.error("短信验证码校验异常, mobile={}",mobile,e);
        }
        return false;
    }

    private static String sendSmsCode0(String mobile) {
        String code = StringUtils.leftPad(new Random().nextInt(10000) +"",4,"0");
        LogUtils.smsLog.info("短信验证码发送, mobile={}, code={}",mobile,code);
//        SMS_203060328
        //TODO 验证码发送
        try {
            JSONObject msg = new JSONObject();
            msg.put("code" , code);
            SendSmsResponse response = sendSms0(mobile,msg.toJSONString(),defautempleteId);
            if(response.getCode().equals("OK")){
                LogUtils.smsLog.info("短信验证码发送成功, mobile={}, code={}, response={}",mobile,code,JSONObject.toJSONString(response));
                return code;
            }else{
                LogUtils.smsLog.warn("短信验证码发送失败, mobile={}, code={}, response={}",mobile,code,JSONObject.toJSONString(response));
            }
        } catch (Exception e) {
            LogUtils.smsLog.error("短信验证码发送异常, mobile={}",mobile,e);
        }
        return "";
    }


    private static SendSmsResponse sendSms0(String mobile, String jsonMsg, String templeteId) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(mobile);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(templeteId);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(jsonMsg);

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }

}
